<script setup>
import { getCurrentRouteQuery } from '@/utils/routerUtils'
import { onMounted, ref } from 'vue'
import {
  addProjectParticipantApi,
  deleteProjectApi,
  findAllWorkGroupsApi,
  findProjectAllParticipantApi,
  findProjectDetailsApi,
  findUserByNameApi,
  updateProjectDetailsApi
} from '@/apis/projectManagement'
import { dayjs, ElMessage, ElMessageBox, genFileId } from 'element-plus'
import { Plus as IconPlus } from '@element-plus/icons-vue'
import router from '@/router'

const pageLoading = ref(true)
const queryParams = ref(getCurrentRouteQuery())
const workGroupList = ref([])
const ownerList = ref([])
const ownerSearchLoading = ref(false)
const participantList = ref([])
const addUserFlag = ref(false)
const editDisable = ref(true)
const participantDisable = ref(true)
const participantAddRequest = ref({
  participantId: null,
  projectId: null
})
const projectDetailsResponse = ref({
  name: '',
  workGroup: {
    gName: ''
  },
  creator: {
    name: ''
  }
})

const updateProjectDetailsRequest = ref({
  id: null,
  name: null,
  groupId: null,
  owner: null,
  status: null,
  description: null
})
const projectImageFileRef = ref()
const onImageFileExceed = (files) => {
  const file = files[0]
  file.uid = genFileId()
  projectImageFileRef.value.clearFiles()
  projectImageFileRef.value.handleStart(file)
}
const onChangeImageFileUpload = (uploadFile) => {
  updateProjectDetailsRequest.value.file = uploadFile.raw
}


const onOwnerRemoteMethod = (name) => {
  ownerSearchLoading.value = true
  findUserByNameApi(name).then(({data}) => {
    ownerList.value = data || []
  }).finally(() => {
    ownerSearchLoading.value = false
  })
}

const onAddParticipantSubmit = () => {
  const filter = participantList.value.filter(item => item.id === participantAddRequest.value.participantId)
  console.log(filter)
  if (filter.length !== 0) {
    ElMessage.warning('当前参与人已存在！')
    return
  }
  addProjectParticipantApi(participantAddRequest.value).then(res => {
    findProjectAllParticipant()
    addUserFlag.value = false
  })
}

const findAllWorkGroups = () => {
  findAllWorkGroupsApi().then(({data}) => {
    workGroupList.value = data || []
  })
}

const findProjectAllParticipant = () => {
  findProjectAllParticipantApi(queryParams.value.id).then(({data}) => {
    participantList.value = data
  })
}


const findProjectDetails = () => {
  findProjectDetailsApi(queryParams.value.id).then(({data}) => {
    projectDetailsResponse.value = data
    updateProjectDetailsRequest.value.id = data.id
    participantAddRequest.value.projectId = data.id
    updateProjectDetailsRequest.value.name = data.name
    updateProjectDetailsRequest.value.groupId = data.workGroup.id
    updateProjectDetailsRequest.value.owner = data.owner.id
    updateProjectDetailsRequest.value.status = data.status
    updateProjectDetailsRequest.value.description = data.description
    updateProjectDetailsRequest.value.description = data.description
    projectDetailsResponse.value.createTime = dayjs(data.createTime).format('YYYY-MM-DD HH:mm:ss')
    projectDetailsResponse.value.updateTime = dayjs(data.updateTime).format('YYYY-MM-DD HH:mm:ss')
  })
}

const onProjectDetailsSubmit = () => {
  updateProjectDetailsApi(updateProjectDetailsRequest.value).then(res => {
    findProjectDetails()
    ElMessage.success('修改成功！')
    editDisable.value = true
  })

}

const deleteProject = () => {
  ElMessageBox.confirm(
      '请确认是否删除项目',
      '删除项目',
      {
        distinguishCancelAndClose: true,
        confirmButtonText: '确认',
        cancelButtonText: '取消',
      }
  )
      .then(() => {
        deleteProjectApi({id: projectDetailsResponse.value.id}).then(res => {
          ElMessage({
            type: 'info',
            message: '删除成功',
          })
          router.back()
        })
      }).catch((action) => {

  })
}

onMounted(() => {
  findProjectDetails()
  onOwnerRemoteMethod('')
  findAllWorkGroups()
  findProjectAllParticipant()
})

</script>

<template>
  <el-breadcrumb separator="/" style="margin-bottom: 36px;">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item :to="{ path: '/system/projectManagement/overview'}">项目总览</el-breadcrumb-item>
    <el-breadcrumb-item>{{ updateProjectDetailsRequest.name }}</el-breadcrumb-item>
  </el-breadcrumb>
  <!--  <el-steps-->
  <!--      style="width: 100%;"-->
  <!--      space="33%"-->
  <!--      :active="updateProjectDetailsRequest.status === 2 ? 3 : projectDetailsResponse.status"-->
  <!--      finish-status="success"-->
  <!--      align-center-->
  <!--  >-->
  <!--    <el-step title="未开始">-->
  <!--      &lt;!&ndash;      <template #title>&ndash;&gt;-->
  <!--      &lt;!&ndash;        <div style="font-size: 14px">&ndash;&gt;-->
  <!--      &lt;!&ndash;          未开始&ndash;&gt;-->
  <!--      &lt;!&ndash;        </div>&ndash;&gt;-->
  <!--      &lt;!&ndash;      </template>&ndash;&gt;-->
  <!--      <template #description>-->
  <!--        <div v-if="projectDetailsResponse.status === 0">-->
  <!--          最近更新时间：{{ dayjs(projectDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}-->
  <!--        </div>-->
  <!--      </template>-->
  <!--    </el-step>-->
  <!--    <el-step title="进行中">-->
  <!--      <template #description>-->
  <!--        <div v-if="projectDetailsResponse.status === 1">-->
  <!--          最近更新时间：{{ dayjs(projectDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}-->
  <!--        </div>-->
  <!--      </template>-->
  <!--    </el-step>-->
  <!--    <el-step title="已完成">-->
  <!--      <template #description>-->
  <!--        <div v-if="projectDetailsResponse.status === 2">-->
  <!--          完成时间：{{ dayjs(projectDetailsResponse.updateTime).format('YYYY/MM/DD HH:mm') }}-->
  <!--        </div>-->
  <!--      </template>-->
  <!--    </el-step>-->
  <!--  </el-steps>-->
  <div style="padding: 24px 220px;">
    <div style=" margin-bottom: 36px;">
      <div style="margin-bottom: 24px; display: flex; justify-content: space-between;">
        <span style="font-size: 18px;">项目基本信息</span>
        <div>
          <el-button v-if="projectDetailsResponse.operateAuth === 1 && !editDisable" @click="editDisable = true"
                     size="small" type="danger">取消
          </el-button>
          <el-button v-if="projectDetailsResponse.operateAuth === 1 && editDisable" @click="editDisable = false"
                     size="small" type="primary">编辑
          </el-button>
          <el-button v-else-if="!editDisable" @click="onProjectDetailsSubmit" size="small" type="primary">确认
          </el-button>
        </div>
      </div>
      <el-form :model="updateProjectDetailsRequest" label-position="left" label-width="auto">
        <div class="form-wrap">
          <div class="form-wrap__left">
            <el-form-item label="项目名">
              <el-input :disabled="editDisable" style="width: 240px;" v-model="updateProjectDetailsRequest.name"
                        placeholder="输入项目名称" clearable />
            </el-form-item>
            <el-form-item label="项目创建人">
              <el-input disabled style="width: 240px;" v-model="projectDetailsResponse.creator.name"
                        placeholder="" clearable />
            </el-form-item>
            <el-form-item label="项目创建时间">
              <el-input disabled style="width: 240px;" v-model="projectDetailsResponse.createTime"
                        placeholder="" clearable />
            </el-form-item>
            <el-form-item label="项目封面图" prop="file">
              <el-upload action="#"
                         :limit="1"
                         :on-exceed="onImageFileExceed"
                         :on-change="onChangeImageFileUpload"
                         ref="projectImageFileRef"
                         :disabled="editDisable"
                         accept=".png,.jpeg,.jpg"
                         :auto-upload="false">
                <el-button :disabled="editDisable" style="width: 240px" :icon="IconPlus">上传</el-button>


              </el-upload>
            </el-form-item>
            <!--            <el-form-item label="任务状态" prop="status" style="margin-right: 0">-->
            <!--              <el-select-->
            <!--                  v-model="updateProjectDetailsRequest.status"-->
            <!--                  style="width: 240px"-->
            <!--                  disabled-->
            <!--              >-->
            <!--                <el-option label="未开始" :value="0"/>-->
            <!--                <el-option label="进行中" :value="1"/>-->
            <!--                <el-option label="已完成" :value="2"/>-->
            <!--                <el-option label="已逾期" :value="3"/>-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
          </div>
          <div class="form-wrap__right">
            <el-form-item label="项目所属工作组">
              <el-select
                  style="width: 240px"
                  v-model="updateProjectDetailsRequest.groupId"
                  placeholder="选择项目所属工作组"
                  clearable
                  :disabled="editDisable"
              >
                <el-option v-for="group in workGroupList" :key="group.id" :label="group.gName" :value="group.id" />
              </el-select>
            </el-form-item>

            <el-form-item label="项目负责人" prop="owner">
              <el-select
                  v-model="updateProjectDetailsRequest.owner"
                  :remote-method="onOwnerRemoteMethod"
                  placeholder="搜索负责人"
                  :loading="ownerSearchLoading"
                  :disabled="editDisable"
                  style="width: 240px"
                  clearable
                  filterable
                  remote
              >
                <el-option
                    v-for="owner in ownerList"
                    :key="owner.id"
                    :label="owner.name"
                    :value="owner.id"
                >
                  <span style="float: left">{{ owner.name }}</span>
                  <span
                      style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ owner.username }}
            </span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="项目更新时间">
              <el-input disabled style="width: 240px;" v-model="projectDetailsResponse.updateTime"
                        placeholder="" clearable />
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div style="margin-bottom: 36px;">
      <div style="margin-bottom: 24px;">
        <span style="font-size: 18px;">项目描述</span>
      </div>
      <el-input style="width: 100%"
                :disabled="editDisable"
                :rows="4"
                :autosize="{minRows: 4, maxRows: 12}"
                type="textarea"
                v-model="updateProjectDetailsRequest.description"
                placeholder="描述下项目"
                clearable />
    </div>
    <div>
      <div style="margin-bottom: 24px; display: flex; justify-content: space-between">
        <span style="font-size: 18px;">项目参与人</span>
        <div>
          <el-button @click="participantDisable = false"
                     v-if="projectDetailsResponse.operateAuth === 1 && participantDisable" type="primary" size="small">
            编辑
          </el-button>
          <el-button @click="participantDisable = true"
                     v-if="!participantDisable" type="danger" size="small">
            取消
          </el-button>
          <el-button @click="participantDisable = true" v-if="!participantDisable" type="primary" size="small">确认
          </el-button>
        </div>
      </div>
      <el-tag
          v-for="tag in participantList"
          :key="tag"
          :type="participantDisable ? 'info' : 'primary'"
          round
          :disable-transitions="false"
          style="margin-right: 8px;"
      >
        {{ tag.name }} - {{ tag.username }}
      </el-tag>
      <el-select
          v-if="addUserFlag"
          size="small"
          class="participant-select"
          v-model="participantAddRequest.participantId"
          :remote-method="onOwnerRemoteMethod"
          placeholder="搜索负责人"
          :loading="ownerSearchLoading"
          :disabled="participantDisable"
          style="width: 140px; margin-right: 12px;"
          clearable
          filterable
          remote
      >
        <el-option
            v-for="owner in ownerList"
            :key="owner.id"
            :label="owner.name"
            :value="owner.id"
        >
          <span style="float: left">{{ owner.name }}</span>
          <span
              style="float: right; color: var(--el-text-color-secondary); font-size: 13px;">
                {{ owner.username }}
            </span>
        </el-option>
      </el-select>
      <el-button v-if="!participantDisable && !addUserFlag" round class="button-new-tag" size="small"
                 @click="addUserFlag = true">
        + 添加
      </el-button>
      <el-button v-if="addUserFlag" round class="button-new-tag" type="danger" size="small"
                 @click="addUserFlag = false">
        取消
      </el-button>
      <el-button v-if="addUserFlag" round class="button-new-tag" type="primary" size="small"
                 @click="onAddParticipantSubmit">
        确认
      </el-button>
    </div>
    <div style="display: flex; justify-content: center; margin-top: 88px;">
      <el-button v-if="projectDetailsResponse.operateAuth === 1" @click="deleteProject" type="danger"
                 style="width: 200px;">删除项目
      </el-button>
    </div>
  </div>
</template>

<style scoped lang="less">
.form-wrap {
  display: flex;
  justify-content: space-between;

  .form-wrap__left {
    //flex: 1;
  }

  .form-wrap__right {
    //flex: 1;
  }
}

:deep(.el-textarea__inner) {
  resize: none;
}

.participant-select {
  :deep(.el-select__wrapper) {
    border-radius: 9999px;
  }
}

</style>